package cn.jekun.shop.common.service;

import java.math.BigDecimal;
import java.sql.Types;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.xml.transform.Source;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.jekun.component.base.exceptions.BusinessException;
import cn.jekun.component.base.utils.SqlUtis;
import cn.jekun.component.base.validator.annotation.Security;
import cn.jekun.component.core.Constants;
import cn.jekun.component.core.bean.gen.ErpMerchandise;
import cn.jekun.component.core.bean.gen.ErpMyShop;
import cn.jekun.component.core.bean.gen.ErpScoreHis;
import cn.jekun.component.core.bean.gen.ErpShop;
import cn.jekun.component.core.bean.gen.ErpShopImage;
import cn.jekun.component.core.service.gen.ErpMerchandiseService;
import cn.jekun.component.core.service.gen.ErpMyShopService;
import cn.jekun.component.core.service.gen.ErpOrdersService;
import cn.jekun.component.core.service.gen.ErpScoreHisService;
import cn.jekun.component.core.service.gen.ErpShopImageService;
import cn.jekun.component.core.service.gen.ErpShopService;

@Service(ShopRecGoodsService.BEAN_NAME)
public class ShopRecGoodsService extends ShopBaseService {
	public static final String BEAN_NAME = "cn.jekun.shop.common.ShopRecGoodsService";
	public static final String NAMESPACE = "SHOP_GOODSMESSAGE";

	@Override
	public String getNamespace() {
		return NAMESPACE;
	}

	@Resource(name = ErpShopService.BEAN_NAME)
	ErpShopService erpShopService;
	
	@Resource(name = ErpShopImageService.BEAN_NAME)
	ErpShopImageService erpShopImageService;
	
	@Resource(name = ErpMerchandiseService.BEAN_NAME)
	ErpMerchandiseService merchandiseService;
	@Resource(name = ErpMyShopService.BEAN_NAME)
	ErpMyShopService erpMyShopService;
    @Resource(name = ErpScoreHisService.BEAN_NAME)
    ErpScoreHisService erpScoreHisService;
    @Resource(name = ErpOrdersService.BEAN_NAME)
	ErpOrdersService erpOrdersService;
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public JSONObject getShopRecGoods(@Security String shopId,@Security String userId) {

		if (StringUtils.isBlank(shopId)) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE, "商家代码不能为空");
		}
		JSONObject jsonObject = new JSONObject();
		Map shopIdMap = new HashMap();
		shopIdMap.put(ErpShop.COL_SHOP_ID, shopId);
		SqlUtis.prepareSql(shopIdMap, SqlUtis.getSQL(shopIdMap, ErpShop.COL_SHOP_ID, Types.VARCHAR, SqlUtis.EQ));

		// 商家信息
		ErpShop erpShop = this.erpShopService.one(shopIdMap);
		if (erpShop == null) {
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE, "商家不存在");
		}
		
		//商家图片
		Map shopImagesMap = new HashMap();
		shopImagesMap.put(ErpShopImage.COL_SHOP_ID, shopId);
		SqlUtis.prepareSql(shopImagesMap
				, SqlUtis.getSQL(shopImagesMap, ErpShopImage.COL_SHOP_ID, Types.VARCHAR, SqlUtis.EQ)
				, SqlUtis.orderBy(ErpShopImage.COL_SORT)
				);
		
		List<ErpShopImage> erpShopImages = this.erpShopImageService.list(shopImagesMap);
		if (erpShopImages==null) {
			jsonObject.put("shopImages", new JSONArray());
		}else {
			jsonObject.put("shopImages", JSONArray.fromObject(erpShopImages));
		}
		
	    Double tempScore = erpShop.getScore();
	    if(tempScore == null){
	    	tempScore = 0.0;
	    }else if(tempScore > 0 && tempScore < 1){
	    	tempScore = 0.5;
	    }else if(tempScore > 1 && tempScore < 2){
	    	tempScore = 1.5;
	    }else if(tempScore > 2 && tempScore <3){
	    	tempScore = 2.5;
	    }else if(tempScore > 3 && tempScore <4){
			tempScore = 3.5;
		}else if(tempScore > 4 && tempScore <5){
			tempScore = 4.5;
		}
	    erpShop.setScore(tempScore);
	    String tempIntroduct = erpShop.getIntroduce();
	    if(tempIntroduct !=null && tempIntroduct.length() > 200){
	    	tempIntroduct = tempIntroduct.substring(0, 200);
	        erpShop.setIntroduce(tempIntroduct);
	    }
		jsonObject.put("shop", erpShop == null ? "[]" : erpShop);
		// 商家特色
		String spe = "";
		List<Map> list = this
				.listBySql("select listagg(c.spe_type_id,',') within GROUP (order by b.shop_id) spe from erp_shop_spe b join erp_spe_type c on (b.spe_type_id = c.spe_type_id) where b.shop_id='"
						+ shopId + "' group by b.shop_id");
		if (list == null || list.size() == 0) {
			spe = "";
		} else {
			spe = list.get(0).get("SPE").toString();
		}
		jsonObject.put("speId", spe);
		// 商家支持的支付方式
		String payments = "";
		List<Map> paymentList = this
				.listBySql("select listagg(a.payment_id, ',') within GROUP(order by a.shop_id) payments from erp_shop_payment a join erp_payment b on (a.payment_id = b.payment_id) where a.shop_id ='"
						+ shopId + "' group by a.shop_id");
		if (paymentList == null || paymentList.size() == 0) {
			payments = "";
		} else {
			payments = paymentList.get(0).get("PAYMENTS").toString();
		}
		jsonObject.put("payments", payments);
		// 商家商品数量
		String totals = "0";
		List<Map> totalList = this.listBySql("select * from ERP_MERCHANDISE a where  a.SHOP_ID = '" + shopId + "' and a.CLOSED = '1' and a.VIRTUAL = '0'");
		if (totalList.size() > 0) {
			totals = "" + totalList.size();
		}
		jsonObject.put("totals", totals);
		// 商家推荐商品信息
		Map shopGoodsMap = new HashMap();
		shopGoodsMap.put("shopId", shopId);
		SqlUtis.prepareSql(shopGoodsMap, SqlUtis.getSQL(shopGoodsMap, "shopId", Types.VARCHAR, SqlUtis.EQ), SqlUtis.getSQL(shopGoodsMap, ErpMerchandise.COL_RECOMMENDED, Types.VARCHAR, SqlUtis.EQ));
		List<ErpMerchandise> ErpMerchandises = this.merchandiseService.list(this.getStatementName("queryShopRecGoodsById"), shopGoodsMap);
		jsonObject.put("shoprecgoods", ErpMerchandises);
		boolean scoreAbleFlag = false;
		//用户是否在商家下单过，用于评分权限判断
		if(userId != null && !userId.equals("")){
		Map scoreAbleMap = new HashMap();
		scoreAbleMap.put("user_id", userId);
		scoreAbleMap.put("shop_id", shopId);
		scoreAbleMap.put("order_status_id", "3");
        SqlUtis.prepareSql(scoreAbleMap,SqlUtis.getSQL(scoreAbleMap,"a.shop_id",Types.VARCHAR,SqlUtis.EQ),
        		SqlUtis.getSQL(scoreAbleMap,"a.user_id",Types.VARCHAR,SqlUtis.EQ),
        		SqlUtis.getSQL(scoreAbleMap, "a.order_status_id",Types.VARCHAR,SqlUtis.EQ));
        scoreAbleFlag = this.erpOrdersService.exists(scoreAbleMap);
		}
		jsonObject.put("scoreAbleFlag", scoreAbleFlag);
        return executeRerutn(jsonObject);

	}

	/**
	 * 
	* @Title: updateScore
	* @Description: 更新评分
	* @param @param shopId
	* @param @param userId
	* @param @param score    设定文件
	* @return void    返回类型
	* @throws
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Transactional
	public void updateScore(@Security String shopId,@Security String userId,@Security String score){
		ErpMyShop erpMyShop = null;
		ErpShop erpShop = null;
		if(StringUtils.isBlank(shopId)){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE, "商家代码不能为空");
		}
		if(StringUtils.isBlank(userId)){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"用户代码不为空");
		}
		if(score ==null || "".equals(score)){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"用户评分不为空");
		}
		int shopScore = Integer.parseInt(score);
		if(shopScore > 5){
			shopScore = 5;
		}
		Map scoreUpdateMap = new HashMap();
		erpMyShop = new ErpMyShop();
		erpMyShop.setScore(shopScore);
		scoreUpdateMap.put(ErpMyShop.COL_SHOP_ID,shopId);
		scoreUpdateMap.put(ErpMyShop.COL_USER_ID, userId);
		scoreUpdateMap.put("erpMyShop",erpMyShop);
		SqlUtis.prepareSql(scoreUpdateMap, SqlUtis.getSQL(scoreUpdateMap,"a."+ErpMyShop.COL_SHOP_ID,Types.VARCHAR,SqlUtis.EQ),
				SqlUtis.getSQL(scoreUpdateMap,"a."+ErpMyShop.COL_USER_ID,Types.VARCHAR,SqlUtis.EQ));
		//更新用户最新的评分
		this.erpMyShopService.update(scoreUpdateMap);
		Map countMap = new HashMap();
		countMap.put(ErpMyShop.COL_SHOP_ID, shopId);
		SqlUtis.prepareSql(countMap,SqlUtis.getSQL(countMap, "a."+ErpMyShop.COL_SHOP_ID,Types.VARCHAR,SqlUtis.EQ));
		Double scoreAvg = this.erpMyShopService.one("SHOP_GOODSMESSAGE.avgScore",countMap);
		System.out.println("====================="+scoreAvg+"========================");
		//更新商家的评分
		erpShop = this.erpShopService.one(shopId);
		if(erpShop == null){
			new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE, "商家不存在");
		}
		Map shopIdMap = new HashMap();
		erpShop = new ErpShop();
		erpShop.setScore(scoreAvg);
		shopIdMap.put(ErpShop.COL_SHOP_ID, shopId);
		shopIdMap.put("erpShop", erpShop);
		SqlUtis.prepareSql(shopIdMap, SqlUtis.getSQL(shopIdMap, "a."+ErpShop.COL_SHOP_ID,Types.VARCHAR,SqlUtis.EQ));
		this.erpShopService.update(shopIdMap);
	}
	
	/**
	 * 
	* @Title: addScoreHis
	* @Description: 记录用户对商家的评分
	* @param @param shopId
	* @param @param userId
	* @param @param score    设定文件
	* @return void    返回类型
	* @throws
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Transactional
	public JSONObject addScoreHis(@ErpScoreHis.AnnoShopId String shopId,@ErpScoreHis.AnnoUserId String userId,@ErpScoreHis.AnnoScoreId String score){
        ErpScoreHis erpScoreHis = null;
        JSONObject jsonObject = new JSONObject();
		if(StringUtils.isBlank(shopId)){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE, "商家代码不能为空");
		}
		if(StringUtils.isBlank(userId)){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"用户代码不为空");
		}
		if(score ==null || "".equals(score)){
			score = "0";
		}
		int shopScore = Integer.parseInt(score);
		if(shopScore > 5){
			shopScore = 5;
		}
		erpScoreHis = new ErpScoreHis();
		erpScoreHis.setShopId(shopId);
		erpScoreHis.setUserId(userId);
		erpScoreHis.setScore(shopScore); //设置评分数
		this.erpScoreHisService.insert(erpScoreHis); //添加记录
		jsonObject.put("message","评分成功");
		return executeRerutn(jsonObject);
	}
	
	/**
	 * 
	* @Title: getScoreHis
	* @Description: 获取用户最近评分的记录
	* @param @param userId 用户代码
	* @param @param shopId 商家代码
	* @param @return    设定文件
	* @return JSONObject    返回类型
	* @throws
	 */
	public JSONObject getScoreHis(@Security String userId,@Security String shopId){
		JSONObject jsonObject = new JSONObject();
		if(StringUtils.isBlank(shopId)){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE, "商家代码不能为空");
		}
		if(StringUtils.isBlank(userId)){
			throw new BusinessException(Constants.ERRORS.VALIDATE_ERROR_CODE,"用户代码不为空");
		}
		Map erpMyShopMap = new HashMap();
		erpMyShopMap.put(ErpMyShop.COL_USER_ID, userId);
		erpMyShopMap.put(ErpMyShop.COL_SHOP_ID, shopId);
		SqlUtis.prepareSql(erpMyShopMap, SqlUtis.getSQL(erpMyShopMap, "a."+ErpMyShop.COL_SHOP_ID,Types.VARCHAR,SqlUtis.EQ),
				SqlUtis.getSQL(erpMyShopMap, "a."+ErpMyShop.COL_USER_ID,Types.VARCHAR,SqlUtis.EQ));
		ErpMyShop  erpMyShop = this.erpMyShopService.one(erpMyShopMap);
//		jsonObject.put("score", erpMyShop.getScore()==null?0.0:erpMyShop.getScore());
//		if(erpMyShop.getScore() == null){
//			jsonObject.put("message","您还没有给商家评过分！");
////			jsonObject.put("code","0");
//			return executeRerutnFail(jsonObject);
//		}
		jsonObject.put("score", erpMyShop.getScore() == null?0:erpMyShop.getScore());
		return executeRerutn(jsonObject);
	}
}
